package edu.gyc.hisecurity.auth;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
@Slf4j
public class MyAccessDecisionManager implements AccessDecisionManager {
    @Override//authentication标示你有哪些角色 configAttributes表示请求需要哪些角色
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
       //遍历请求url的角色需求与当前用户的角色进行对比
        for (ConfigAttribute configAttribute : configAttributes) {
            if ("ROLE_login".equals(configAttribute.getAttribute())) { //表示用户已经登录
                 return;

            }
            //authorities当前用户的角色
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            for (GrantedAuthority authority : authorities) {
                if (authority.getAuthority().equals(configAttribute.getAttribute())) {
                    return;  //表示用户已拥有一个请求需求的角色
                }
            }
        }
        throw new AccessDeniedException("非法请求！");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
